<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
            <!-- <el-form-item label="协议标题" prop="title">
          <el-input
            v-model="queryParams.title"
            placeholder="请输入协议标题"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>-->
            <el-form-item label="活动类型" prop="classify">
                <el-select v-model="queryParams.pageSign" placeholder="活动类型" clearable @change='changeType'>
                    <el-option v-for="dict in dict.type.app_promotion_type" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="启用状态" prop="classify">
                <el-select v-model="queryParams.enabled" placeholder="启用状态" clearable>
                    <el-option label="启用" value="true" />
                    <el-option label="禁用" value="false" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索
                </el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['mall:banner:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                    v-hasPermi="['mall:banner:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                    @click="handleDeleteAll" v-hasPermi="['mall:banner:remove']">批量删除</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table border v-loading="loading" :data="rotationChartList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="展示顺序" align="center" prop="orderNum" width="80" />
            <el-table-column label="背景色" align="center" prop="backgroundColor" width="100">
                <template slot-scope="scope">
                    <el-color-picker v-model="scope.row.backgroundColor" disabled></el-color-picker>
                </template>
            </el-table-column>
            <el-table-column label="客户端类型" prop="clientType" align="center" width="200">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.client_client_type" :value="scope.row.clientType" />
                </template>
            </el-table-column>
            <el-table-column label="页面标记" prop="pageSign" align="center" width="200">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.client_page_sign" :value="scope.row.pageSign" />
                </template>
            </el-table-column>
            <el-table-column label="缩略图片" align="center" width="150">
                <template slot-scope="scope">
                    <el-image :src="scope.row.imageUrl"></el-image>
                </template>
            </el-table-column>
            <el-table-column label="启用状态" align="center" width="100">
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.enabled" :active-value="true" :inactive-value="false"
                        @change="handleEnabledStatusChange(scope.row)"></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="跳转地址" align="center" prop="path" width="500" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdateTime(scope.row)"
                      v-hasPermi="['mall:banner:time:edit']">修改时间</el-button>
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="openUpdateImageView(scope.row)"
                      v-hasPermi="['mall:banner:image:edit']">更改图片</el-button>
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['mall:banner:edit']">修改</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['mall:banner:remove']">删除</el-button>
                    <!-- <el-button size="mini" type="text" icon="el-icon-share" @click="handleDetal(scope.row)"
            v-hasPermi="['system:notice:remove']">详情</el-button>-->
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
            @pagination="getList" />

        <!-- 添加或修改轮播对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="550px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="活动类型" prop="clientType">
                    <el-select v-model="form.pageSign" placeholder="活动类型" clearable>
                        <el-option v-for="dict in dict.type.app_promotion_type" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="图片" prop="imageUrl" label-width="100px">
                    <el-upload action="#" list-type="picture-card" :auto-upload="false" :file-list="imageFileList"
                        :class="{ 'imgMax': imageFileList.length }" :on-remove="handleRemove"
                        :on-preview="handlePictureCardPreview" :on-change="changeImg" ref="upload">
                        <i slot="default" class="el-icon-plus"></i>
                        <div v-if="!imageFileList.length" class="el-upload__tip" slot="tip" style="color: red;">
                            <div v-if="form.clientType == 'WECHAT_MP' || form.clientType == 'APP'">
                                请上传大小为570*400(px),格式为png、jpg格式的图片</div>
                            <div v-else>请上传大小为800*530(px),格式为png、jpg格式的图片</div>
                        </div>
                        <div slot="file" slot-scope="{ file }">
                            <img class="el-upload-list__item-thumbnail" :src="file.url" alt />
                            <span class="el-upload-list__item-actions">
                                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                                    <i class="el-icon-zoom-in"></i>
                                </span>
                                <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                                    <i class="el-icon-delete"></i>
                                </span>
                            </span>
                        </div>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" :src="dialogImageUrl" alt />
                    </el-dialog>
                </el-form-item>
                <el-form-item label="开始时间" prop="startTime" class="start">
                  <el-date-picker v-model="form.startTime" type="datetime" placeholder="选择日期时间"
                    value-format="yyyy-MM-dd HH:mm:ss" :show-overflow-tooltip="true" ></el-date-picker>
                </el-form-item>
                <el-form-item label="结束时间" prop="endTime" class="start">
                  <el-date-picker v-model="form.endTime" type="datetime" placeholder="选择日期时间"
                    value-format="yyyy-MM-dd HH:mm:ss" :show-overflow-tooltip="true" ></el-date-picker>
                </el-form-item>
                <el-form-item label="是否外链">
                    <el-radio-group v-model="form.isFrame">
                        <el-radio v-for="dict in dict.type.link_is_frame" :key="dict.value" :label="dict.value">{{
                            dict.label }}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="跳转地址" prop="path">
                    <el-input v-model="form.path" />
                </el-form-item>
                <el-form-item label="显示顺序" prop="orderNum">
                    <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
                </el-form-item>
                <el-form-item label="背景色" prop="orderNum">
                    <el-color-picker v-model="form.backgroundColor"></el-color-picker>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 更改图片对话框 -->
        <el-dialog v-dialogDragWidth v-dialogDragHeight v-dialogDrag :title="title" :visible.sync="openChangeImageView" width="500px" append-to-body>
          <el-form ref="form" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="图片地址" prop="imageUrl">
              <el-upload action="#" list-type="picture-card" :auto-upload="false"
                :on-remove="handleRemove" :on-preview="handlePictureCardPreview" :on-change="changeImg">
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="{ file }">
                  <img class="el-upload-list__item-thumbnail" :src="file.url" alt />
                  <span class="el-upload-list__item-actions">
                    <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <span v-if="!disabled" class="el-upload-list__item-delete">
                      <i class="el-icon-download"></i>
                    </span>
                    <span v-if="!disabled" class="el-upload-list__item-delete"
                      @click="handleRemove(file)">
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </div>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt />
              </el-dialog>
            </el-form-item>
            <el-form-item label="展示顺序" prop="orderNum">
              <el-input-number v-model="form.orderNum"></el-input-number>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="changeImage">确 定</el-button>
            <el-button @click="openChangeImageView = false">取 消</el-button>
          </div>
        </el-dialog>

    </div>
</template>

<script>
import {
    listAotationChart,
    getAotationChart,
    delAotationChart,
    addAotationChart,
    updateAotationChart,
    handleEnabledChange,
    handleImageChange
} from "@/api/mallAdmin/rotationChart";
import axios from "axios";
import { getToken } from "@/utils/auth";

export default {
    name: "homeIndex",
    dicts: ["app_promotion_type", "link_is_frame", "client_page_sign",'client_client_type'],
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 2,
            // 轮播数据
            rotationChartList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                title: undefined,
                clientType: 'APP',
                createBy: undefined,
                pageSign: 'BARGAIN',
                salaId: '0',
                paramMap: {
                  mallId: '',
                },
            },
            // 表单参数
            form: {
                isFrame: true,
                pageSign: '',
                salaId: '0',
                clientType: 'APP',
                backgroundColor: '#000'
            },
            // 轮播图
            dialogImageUrl: "",
            dialogVisible: false,
            disabled: false,
            imageFileList: [],
            headers: {
                Authorization: "Bearer " + getToken(),
                "Content-Type": "multipart/form-data"
            },
            // 表单校验
            rules: {
                clientType: [
                    { required: true, message: "客户端类型不能为空", trigger: "change" }
                ],
                imageUrl: [
                    { required: true, message: "背景图不能为空", trigger: "blur" },
                    {validator:(rule,value,callback)=>{
                        console.log(this.form.imageUrl)
                        if(!this.form.imageUrl){
                            callback(new Error('背景图不能为空'))
                        } else {
                            callback()
                        }
                    }, trigger: "blur"}
                ]
            },
            openChangeImageView: false,
        };
    },
    created() {
        this.getList();
    },
    methods: {
        /** 获取轮播图列表 */
        getList() {
            this.loading = true;
            listAotationChart(this.queryParams).then(response => {
                this.rotationChartList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.imageFileList = []
            this.form = {
                imageUrl: undefined,
                clientType: 'APP',
                isFrame: true,
                path: undefined,
                orderNum: undefined,
                backgroundColor: '#000',
                status: '0',
                isFrame: 'true',
                pageSign: this.queryParams.pageSign,
                salaId: '0',
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id);
            this.single = selection.length != 1;
            this.multiple = !selection.length;
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加轮播图";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            this.form = JSON.parse(JSON.stringify(row)) ;
            this.form.isFrame = this.form.isFrame.toString()
            this.imageFileList = [{ url: row.imageUrl }]
            this.open = true;
            this.title = "修改轮播图";
        },
        /** 提交按钮 */
        submitForm() {
            const loading = this.$loading({
                lock: true,
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.7)"
            });
            if (this.form.id) {
                updateAotationChart(this.form).then(response => {
                    console.log(response)
                    this.$modal.msgSuccess("修改成功");
                    this.open = false;
                    this.getList();
                    loading.close();
                }).catch((res)=>{
                    loading.close()
                });
            } else {
                addAotationChart(this.form).then(response => {
                    console.log(response)
                    this.$modal.msgSuccess("新增成功");
                    this.open = false;
                    this.getList();
                    loading.close();
                }).catch((res)=>{
                    loading.close()
                });;
            }

        },
        /** 单个删除按钮操作 */
        handleDelete(row) {
            const id = row.id;
            this.$modal
                .confirm("是否确认删除数据项？")
                .then(function () {
                    return delAotationChart(id);
                })
                .then(() => {
                    this.getList();
                    this.$modal.msgSuccess("删除成功");
                })
                .catch(() => { });
        },
        // 批量删除
        handleDeleteAll() {
            var ids = this.ids;
            this.$modal
                .confirm("是否确认删除？")
                .then(function () {
                    return delAotationChartAll(ids);
                })
                .then(() => {
                    this.getList();
                    this.$modal.msgSuccess("删除成功");
                })
                .catch(() => { });
        },
        changeType(val) {
            console.log(val)
        },
        // 上传轮播图
        handleRemove(file, fileList) {
            this.form.imageUrl = null;
            this.imageFileList = []
            console.log(file, fileList);
        },
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.raw.url;
            this.dialogVisible = true;
        },
        changeImg(file, fileList) {
            const loading = this.$loading({
                lock: true,
                text: "上传中...",
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.7)"
            });
            this.imageFileList = [file]
            let formData = new FormData();
            formData.append("file", file.raw);
            axios.post(`${process.env.VUE_APP_BASE_API}/oss/common/upload`, formData, {
                headers: this.headers
            }).then(res => {
                loading.close();
                if (res.status == 200) {
                    let data = res.data;
                    if (data.code == 200) {
                        this.$modal.msgSuccess("上传成功");
                        this.form.imageUrl = data.data.url;
                        this.form.imageId = data.data.id;
                    }
                }
            })
        },
        // 启用状态修改
        handleEnabledStatusChange(row) {
            let text = row.enabled === true ? "启用" : "禁用";
            this.$modal.confirm('确认"' + text + '"此轮播图吗？')
                .then(function () {
                    return handleEnabledChange(
                        row.id,
                        row.enabled
                    );
                }).then(() => {
                    this.$modal.msgSuccess(text + "成功");
                }).catch(function () {
                    row.enabled = row.enabled === true ? false : true
                });
        },
        openUpdateImageView(row){
          this.imageFileList = [];
          this.title = "更换图片";
          this.openChangeImageView = true;
          this.form = { ...row };
        },
        //更换图片
        changeImage(){
          if(!this.form.orderNum){
            this.$modal.msgError("请填写排序编号");
            return;
          }

          if (!this.imageFileList) {
            this.$modal.msgError("请选择图片");
            return;
          }

          const _this = this;
          this.$modal.confirm("确认更换轮播图图片吗？").then(function () {
            const loading = _this.$loading({
              lock: true,
              text: "上传中...",
              spinner: "el-icon-loading",
              background: "rgba(0, 0, 0, 0.7)"
            });
            let formData = new FormData();
            formData.append("file", _this.imageFileList[0].raw);
            axios.post(`${process.env.VUE_APP_BASE_API}/oss/common/upload`, formData, {
              headers: _this.headers
            }).then(res => {
              if (res.status == 200) {
                let data = res.data;
                if (data.code == 200) {
                  const changeImageData = {
                    imageId: data.data.id,
                    imageUrl: data.data.url,
                    countdown: _this.form.countdown,
                    orderNum: _this.form.orderNum
                  }
                  handleImageChange(_this.form.id, changeImageData).then(res=>{
                    _this.$modal.msgSuccess("更换成功");
                    _this.getList();
                    _this.openChangeImageView = false;
                  });
                } else {
                  _this.$message.error("上传文件失败" + res.data.msg);
                }
              }
            }).finally(res => {
              loading.close();
            });
          }).catch(function(err) {
            console.log(err)
            _this.$modal.msgError("更换图片出错");
          });
        },
    }
};
</script>
<style scoped lang="scss">
::v-deep .imgMax .el-upload--picture-card {
    display: none;
}
::v-deep .el-color-picker__mask{
    display: none;
}
</style>
